<!-- 可拖拽表单组件 -->
<template>
  <div class="form">
    <el-form
      :model="data"
      :rules="rules"
      ref="form"
      :label-width="labelWidth"
      class="demo-ruleForm"
      v-bind="{...formConfig}"
      :inline="inline"
    >
      <draggable class="dragApi" v-model="form_data" :options="dragOptions">
        <transition-group :name="'flip-list'">
          <div v-for="(val, key) in form_data" :key="key">
            <el-form-item 
              v-if="val.isShow"
              :label="val.label"
              :prop="val.name"
            >
              <el-row type="flex">
                <el-col :span="val.span ? val.span:20">
                  <!-- 输入框 -->
                  <el-input
                    v-if="val.type === 'input'"
                    v-model="data[val.name]"
                    :placeholder="val.placeholder || '请输入'"
                    v-bind="{...val.config}"
                  ></el-input>
                  <!-- 选择框 -->
                  <el-select
                    v-if="val.type === 'select'"
                    v-model="data[val.name]"
                    :placeholder="val.placeholder || '请选择'"
                    v-bind="{...val.config}"
                  >
                    <el-option v-for="(item, key) in val.groups" :key="key" v-bind="{...item}"></el-option>
                  </el-select>
                  <!-- 日期选择器 -->
                  <el-date-picker
                    v-if="val.type === 'date_picker'"
                    type="date"
                    :placeholder="val.placeholder || '选择日期'"
                    v-model="data[val.name]"
                    style="width: 100%;"
                    v-bind="{...val.config}"
                  ></el-date-picker>
                  <!-- 时间选择器 -->
                  <el-time-picker
                    v-if="val.type === 'time_picker'"
                    :placeholder="val.placeholder || '选择时间'"
                    v-model="data[val.name]"
                    style="width: 100%;"
                    v-bind="{...val.config}"
                  ></el-time-picker>
                  <!-- 切换按钮 -->
                  <el-switch
                    v-if="val.type === 'switch'"
                    v-model="data[val.name]"
                    v-bind="{...val.config}"
                  ></el-switch>
                  <!-- 多选框 -->
                  <el-checkbox-group
                    v-if="val.type === 'checkbox'"
                    v-model="data[val.name]"
                    v-bind="{...val.config}"
                  >
                    <el-checkbox v-for="(item, key) in val.groups" :key="key" v-bind="{...item}"></el-checkbox>
                  </el-checkbox-group>
                  <!-- 单选框 -->
                  <el-radio-group
                    v-if="val.type === 'radio'"
                    v-model="data[val.name]"
                    v-bind="{...val.config}"
                    @change="(item) => radioChange(item,val)"
                  >
                    <el-radio v-for="(item, key) in val.groups" :key="key" v-bind="{...item}"></el-radio>
                  </el-radio-group>
                  <!-- 文本域 -->
                  <el-input
                    v-if="val.type === 'textarea'"
                    type="textarea"
                    :placeholder="val.placeholder || '请输入'"
                    v-model="data[val.name]"
                    v-bind="{...val.config}"
                  ></el-input>
                  <!-- 文件上传 -->
                  <Upload
                    v-if="val.type === 'data_upload'"
                    type="data_upload"
                    :ref="val.name"
                    :upload_name="val.name"
                    @onSuccess="onSuccess"
                    @onRemove="onRemove"
                    @onPreview="onPreview"
                    :config="val.config"
                    :message="val.message"
                  />
                  <!-- 图片上传 -->
                  <Upload
                    v-if="val.type === 'image_upload'"
                    type="image_upload"
                    :ref="val.name"
                    :upload_name="val.name"
                    :config="val.config"
                    @onImgSuccess="onImgSuccess"
                    @onImgRemove="onImgRemove"
                    :message="val.message"
                  />
                </el-col>
                <el-col :span="4">
                  <slot name="form-icon" :data="val"></slot>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </transition-group>
      </draggable>

      <el-form-item class="form_footer">
        <el-button type="primary" @click="submitForm('form')">{{sumbitName}}</el-button>
        <el-button v-if="showReset" @click="resetForm('form')">{{resetName}}</el-button>
        <!-- 放置额外的按钮 -->
        <slot name="button"></slot>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import Upload from "@/components/common/upload";
export default {
  name: "drag",
  data() {
    return {
      data: {},
      rules: {},
      form_data: this.formData,
      dragabled:false
    };
  },
  mounted() {
    this.createForm();
  },
  props: {
    // 表单配置
    formConfig: {
      type: Object
    },
    // 表单数据
    /**
     * 数据格式(以文本框为例)
     * [{
          name: "name",//表单元素名称
          label: "姓名",//标题
          value: "",//默认值
          type: "input",//表单类型
          span:"12",//表单长度，详情参考element的栅格布局
          // 可根据需要添加属性
          rules: [
            // 表单规则，详情参考element组件文档
            { required: true, message: "请输入活动名称", trigger: "blur" },
            { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
          ]
        }]
     */
    formData: {
      type: Array,
      required: true,
      default: () => {
        return [];
      }
    },
    // 标题宽度
    labelWidth: {
      type: String,
      default: () => {
        return "100px";
      }
    },
    inline: {
      type: Boolean
    },
    sumbitName: {
      type: String,
      default: () => {
        return "提交";
      }
    },
    showReset: {
      type: Boolean,
      default: () => {
        return true;
      }
    },
    resetName: {
      type: String,
      default: () => {
        return "重置";
      }
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: "description",
        disabled: !this.dragabled,
        ghostClass: "ghost"
      };
    }
  },
  components: { Upload, draggable },
  methods: {
    // 初始化表单数据
    createForm() {
      let data = {},
        rules = {},
        fd = this.form_data;
      for (var idx in fd) {
        data[fd[idx].name] = fd[idx].value;
        if ("rules" in fd[idx]) {
          rules[fd[idx].name] = fd[idx].rules;
        }
      }
      this.data = data;
      this.rules = rules;
    },
    // 处理表单元素
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = {
            valid,
            data: this.data
          };
          this.$emit("submit", formData);
        } else {
          throw "error submit!!";
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      let fd = this.formData;
      this.$refs[formName].resetFields();
      for (var idx in fd) {
        if (fd[idx].type === "data_upload" || fd[idx].type === "image_upload") {
          this.$refs[fd[idx].name][0].$children[0].clearFiles();
        }
      }
      this.$emit("reset", true);
    },
    // 处理单选框展示子级组件
    radioChange(val, data) {
      if (data.isChild) {
        for (var idx in data.groups) {
          if (data.groups[idx].label === val) {
            this.radioHandler(data.groups[idx].childList,data);
          }
        }
      }
    },
    radioHandler(arr,data){
      for(var i in data.groups){
        let cl = data.groups[i].childList;
        for(var j in cl){
          for(var k in this.form_data){
            if(cl[j] === this.form_data[k].name){
              this.form_data[k].isShow = false;
            }
          }
        }
      }

      for(var idx in arr){
        for(var idx2 in this.form_data){
          if(arr[idx] === this.form_data[idx2].name){
            this.form_data[idx2].isShow = true;
            console.log(this.form_data[idx2]);
          }
        }
      }
    },
    // 接受文件上传成功
    onSuccess(e) {
      console.log("onSuccess", e);
      this.data[e.upload_name] = e.fileList;
    },
    // 接受文件移除
    onRemove(e) {
      console.log("onRemove", e);
      this.data[e.upload_name] = e.fileList;
    },
    // 接受文件预览
    onPreview(e) {
      console.log("onPreview", e);
      this.data[e.upload_name] = e.fileList;
    },
    // 接受图片上传成功
    onImgSuccess(e) {
      console.log("onImgSuccess", e);
      this.data[e.upload_name] = e.fileList;
    },
    // 接受图片移除
    onImgRemove(e) {
      console.log("onImgRemove", e);
      this.data[e.upload_name] = e.fileList;
    }
  },
  watch: {
    formData(val) {
      if (val.length != this.form_data.length) {
        this.form_data = val;
      }
    },
    form_data(val) {
      this.$emit("formDrag", val);
      this.createForm();
    }
  }
};
</script>
<style lang='scss'>
.demo-ruleForm {
  .form_footer {
    margin-top: 40px;
    .el-form-item__content {
      margin: 0 !important;
    }
  }
}
.flip-list-move {
  transition: transform 0.5s;
}
</style>